package com.soul.doc.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.soul.common.exception.BaseException;
import com.soul.common.utils.ListUtil;
import com.soul.doc.bean.dto.CollectionDto;
import com.soul.doc.bean.po.LoveMusicPo;
import com.soul.doc.bean.po.SongListMusicPo;
import com.soul.doc.mapper.SongListMusicMapper;
import com.soul.doc.service.SongListMusicService;
import com.soul.common.service.BaseService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 歌单收藏的歌曲 服务实现类
 * </p>
 *
 * @author sws
 * @since 2023-12-06 16:32:36
 */
@Service
public class SongListMusicServiceImpl extends BaseService<SongListMusicMapper, SongListMusicPo> implements SongListMusicService {
    @Override
    public boolean addSongListMusic(CollectionDto collectionDto){
        if (!StpUtil.isLogin()){
            throw new BaseException("未登录");
        }
        List<SongListMusicPo> list = this.getLambadaQueryWrapper().eq(SongListMusicPo::getSongListId, collectionDto.getSongListId()).list();
        List<Long> musicIds = ListUtil.toValueList(list, SongListMusicPo::getMusicId);
        if (ObjectUtil.isNotEmpty(musicIds) && musicIds.contains(collectionDto.getMusicId())){
            if (ObjectUtil.equals(collectionDto.getType(),"remove")){
                // 取消收藏
                this.lambdaUpdate()
                        .eq(SongListMusicPo::getSongListId, collectionDto.getSongListId())
                        .eq(SongListMusicPo::getMusicId, collectionDto.getMusicId())
                        .remove();
                return true;
            }
            return false;
        }
        SongListMusicPo loveSongListPo = new SongListMusicPo();
        loveSongListPo.setSongListId(collectionDto.getSongListId())
                .setMusicId(collectionDto.getMusicId());
        Long maxSort = this.getMaxSort(SongListMusicPo::getSongListId, collectionDto.getSongListId());
        loveSongListPo.setSort(maxSort);
        this.save(loveSongListPo);
        return true;
    }

    @Override
    public List<SongListMusicPo> querySongListMusics(Long songListId){
        List<SongListMusicPo> list = this.getLambadaQueryWrapper().eq(SongListMusicPo::getSongListId, songListId).list();
        return list;
    }
}
